<template>
  <div class="messages-container">
    <div class="page-header agri-page-header">
      <div class="page-title agri-page-title">
        <el-icon><Bell /></el-icon>
        <span>消息中心</span>
      </div>
      <div class="page-actions agri-page-actions">
        <el-button @click="handleMarkAllRead" :disabled="unreadCount === 0" type="primary" plain>
          全部已读
        </el-button>
        <el-button @click="handleClearMessages" :disabled="notifications.length === 0" plain>
          清空消息
        </el-button>
      </div>
    </div>

    <el-card v-loading="loading" class="agri-card">
      <template #header>
        <div class="card-header">
          <div class="card-title">
            <span>消息列表</span>
            <el-badge :value="unreadCount" :hidden="unreadCount === 0" type="danger" />
          </div>
          <div class="card-actions">
            <el-radio-group v-model="messageFilter" size="small">
              <el-radio-button label="all">全部</el-radio-button>
              <el-radio-button label="unread">未读</el-radio-button>
              <el-radio-button label="system">系统</el-radio-button>
              <el-radio-button label="order">订单</el-radio-button>
              <el-radio-button label="warning">提醒</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </template>

      <div v-if="filteredNotifications.length === 0" class="empty-data">
        <el-empty description="暂无消息" />
      </div>

      <div v-else class="message-list">
        <div
          v-for="item in filteredNotifications"
          :key="item.id"
          class="message-item"
          :class="{ 'unread': !item.read }"
          @click="handleReadMessage(item)"
        >
          <div class="message-icon" :class="item.type">
            <el-icon>
              <component :is="getMessageIcon(item.type)"></component>
            </el-icon>
          </div>
          <div class="message-content">
            <div class="message-header">
              <h3 class="message-title">{{ item.title }}</h3>
              <span class="message-time">{{ item.time }}</span>
            </div>
            <div class="message-body">
              <p>{{ item.content }}</p>
            </div>
            <div class="message-footer">
              <el-tag size="small" :type="getTagType(item.type)">
                {{ getTagText(item.type) }}
              </el-tag>
              <div class="message-actions">
                <el-button size="small" text @click.stop="handleMarkRead(item)" v-if="!item.read">
                  标为已读
                </el-button>
                <el-button size="small" text @click.stop="handleDeleteMessage(item)">
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="pagination-container" v-if="notifications.length > pageSize">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          layout="prev, pager, next"
          :total="filteredNotifications.length"
        />
      </div>
    </el-card>

    <!-- 消息详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="currentMessage ? currentMessage.title : '消息详情'"
      width="500px"
      @closed="currentMessage = null"
    >
      <div v-if="currentMessage" class="message-detail">
        <div class="message-meta">
          <span class="message-type">{{ getTagText(currentMessage.type) }}</span>
          <span class="message-time">{{ currentMessage.time }}</span>
        </div>
        <div class="message-detail-content">
          <p>{{ currentMessage.content }}</p>
        </div>
        <div class="message-detail-actions">
          <el-button type="primary" @click="detailDialogVisible = false">关闭</el-button>
          <el-button 
            @click="handleProcessMessage" 
            v-if="currentMessage.actionType"
          >
            {{ currentMessage.actionText || '处理' }}
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useAppStore } from '../../store';
import { Bell, Warning, Document, Message } from '@element-plus/icons-vue';
import { useUserStore } from '../../store';

// 路由和状态管理
const router = useRouter();
const appStore = useAppStore();
const userStore = useUserStore();

// 消息过滤和分页
const messageFilter = ref('all');
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);

// 对话框控制
const detailDialogVisible = ref(false);
const currentMessage = ref(null);

// 从应用状态获取通知
const notifications = computed(() => appStore.notifications);

// 未读消息数量
const unreadCount = computed(() => {
  return notifications.value.filter(item => !item.read).length;
});

// 过滤后的通知列表
const filteredNotifications = computed(() => {
  let result = [...notifications.value];

  // 应用过滤
  if (messageFilter.value === 'unread') {
    result = result.filter(item => !item.read);
  } else if (messageFilter.value !== 'all') {
    result = result.filter(item => item.type === messageFilter.value);
  }

  // 按时间倒序排序
  result = result.sort((a, b) => {
    const dateA = new Date(a.timestamp || Date.now());
    const dateB = new Date(b.timestamp || Date.now());
    return dateB - dateA;
  });

  return result;
});

// 获取通知图标
function getMessageIcon(type) {
  switch (type) {
    case 'warning':
      return Warning;
    case 'notification':
      return Bell;
    case 'document':
      return Document;
    default:
      return Message;
  }
}

// 获取标签类型
function getTagType(type) {
  switch (type) {
    case 'warning': return 'warning';
    case 'order': return 'primary';
    case 'system': return 'info';
    case 'price': return 'success';
    default: return 'info';
  }
}

// 获取标签文本
function getTagText(type) {
  switch (type) {
    case 'warning': return '提醒';
    case 'order': return '订单';
    case 'system': return '系统';
    case 'price': return '价格';
    default: return '通知';
  }
}

// 标记消息为已读
async function handleMarkRead(message) {
  console.log(`手动标记消息[${message.id}]为已读`);
  if (!message.read) {
    try {
      const success = await appStore.markNotificationAsRead(message.id);
      console.log(`标记消息[${message.id}]为已读结果:`, success ? '成功' : '失败');
      
      if (success) {
        // 更新本地消息状态
        message.read = true;
        ElMessage.success('已标记为已读');
        
        // 刷新未读计数
        setTimeout(() => {
          appStore.fetchUnreadCount();
        }, 500);
      }
    } catch (error) {
      console.error(`标记消息[${message.id}]为已读失败:`, error);
      ElMessage.error('标记已读失败: ' + (error.message || '未知错误'));
    }
  } else {
    console.log(`消息[${message.id}]已经是已读状态，不需要标记`);
  }
}

// 标记所有消息为已读
async function handleMarkAllRead() {
  console.log('标记所有消息为已读');
  try {
    const success = await appStore.markAllNotificationsAsRead();
    console.log('标记所有消息为已读结果:', success ? '成功' : '失败');
    
    if (success) {
      // 更新所有本地消息状态
      if (filteredNotifications.value && filteredNotifications.value.length > 0) {
        filteredNotifications.value.forEach(msg => msg.read = true);
      }
      
      ElMessage.success('已将所有消息标记为已读');
      
      // 刷新未读计数
      setTimeout(() => {
        appStore.fetchUnreadCount();
      }, 500);
    }
  } catch (error) {
    console.error('标记所有消息为已读失败:', error);
    ElMessage.error('标记所有已读失败: ' + (error.message || '未知错误'));
  }
}

// 清空消息
function handleClearMessages() {
  ElMessageBox.confirm(
    '确定要清空所有消息吗？此操作不可撤销。',
    '清空确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const success = await appStore.clearAllNotifications();
    if (success) {
      ElMessage.success('已清空所有消息');
    }
  }).catch(() => {});
}

// 查看消息详情
async function handleReadMessage(message) {
  console.log('查看消息详情:', message);
  currentMessage.value = message;
  detailDialogVisible.value = true;
  
  // 标记为已读（如果消息未读）
  if (!message.read) {
    console.log(`消息[${message.id}]未读，标记为已读`);
    try {
      const success = await appStore.markNotificationAsRead(message.id);
      console.log(`标记消息[${message.id}]为已读结果:`, success ? '成功' : '失败');
      
      if (success) {
        // 更新本地消息状态
        message.read = true;
        
        // 延迟刷新未读计数
        setTimeout(() => {
          appStore.fetchUnreadCount();
        }, 500);
      }
    } catch (error) {
      console.error(`标记消息[${message.id}]为已读失败:`, error);
    }
  } else {
    console.log(`消息[${message.id}]已经是已读状态，不需要标记`);
  }
}

// 删除消息
function handleDeleteMessage(message) {
  ElMessageBox.confirm(
    '确定要删除这条消息吗？',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    // 实现删除消息的逻辑
    const success = await appStore.deleteNotification(message.id);
    if (success) {
      ElMessage.success('消息已删除');
    }
  }).catch(() => {});
}

// 处理消息相关操作
function handleProcessMessage() {
  if (!currentMessage.value) return;
  
  // 根据消息类型和操作类型进行处理
  const message = currentMessage.value;
  
  if (message.actionRoute) {
    detailDialogVisible.value = false;
    router.push(message.actionRoute);
  } else {
    ElMessage.info('暂无可处理的操作');
  }
}

// 组件挂载
onMounted(async () => {
  // 检查是否登录，如果未登录则不获取通知
  const token = localStorage.getItem('token');
  if (!token) {
    console.log('未检测到登录状态，跳过通知请求');
    return;
  }
  
  // 从后端获取消息
  loading.value = true;
  try {
    console.log('消息中心准备获取通知，确认已登录');
    // 添加一个小延迟，确保登录流程已完成
    setTimeout(async () => {
      try {
        await appStore.fetchNotifications();
      } catch (error) {
        console.error('延迟后加载消息失败', error);
        // 如果加载失败，显示提示
        ElMessage.warning('通知加载失败，可能是网络问题，请稍后重试');
      } finally {
        loading.value = false;
      }
    }, 1000); // 延迟1秒后获取通知
  } catch (error) {
    console.error('加载消息初始化失败', error);
    loading.value = false;
  }
});
</script>

<style scoped>
.messages-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.page-title .el-icon {
  margin-right: 8px;
  font-size: 24px;
  color: var(--primary-color);
}

.page-actions {
  display: flex;
  gap: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-weight: bold;
  font-size: 16px;
}

.message-list {
  margin-bottom: 20px;
}

.message-item {
  display: flex;
  padding: 15px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  transition: background-color 0.3s;
  cursor: pointer;
}

.message-item:hover {
  background-color: var(--el-fill-color-light);
}

.message-item.unread {
  background-color: var(--primary-color-bg);
}

.message-item:last-child {
  border-bottom: none;
}

.message-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 15px;
  color: white;
  flex-shrink: 0;
}

.message-icon.warning {
  background-color: var(--el-color-warning);
}

.message-icon.system {
  background-color: var(--el-color-info);
}

.message-icon.order {
  background-color: var(--el-color-primary);
}

.message-icon.price {
  background-color: var(--el-color-success);
}

.message-content {
  flex: 1;
  min-width: 0;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.message-title {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
}

.message-time {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  white-space: nowrap;
}

.message-body {
  margin-bottom: 10px;
  color: var(--el-text-color-regular);
}

.message-body p {
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.message-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.message-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.empty-data {
  padding: 40px 0;
  text-align: center;
}

.message-detail {
  padding: 10px;
}

.message-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.message-detail-content {
  padding: 15px 0;
  border-top: 1px solid var(--el-border-color-lighter);
  border-bottom: 1px solid var(--el-border-color-lighter);
  margin-bottom: 20px;
}

.message-detail-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .page-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .card-actions {
    width: 100%;
    margin-top: 10px;
  }
}
</style> 